package com.xyzq.cgate.core.plugin.pre;

import com.google.common.base.Splitter;
import com.xyzq.cgate.common.enums.PluginDetailEnum;
import com.xyzq.cgate.common.rule.custom.entity.ComplexRule;
import com.xyzq.cgate.core.cache.CacheManager;
import com.xyzq.cgate.core.plugin.AbstractPlugin;
import com.xyzq.cgate.core.plugin.IPlugin;
import com.xyzq.cgate.core.plugin.IPluginChain;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.StringTokenizer;


/**
 * @Description:
 * @author chenchen
 * @date 2019/6/19 13:57
 */
public class FireWallPlugin extends AbstractPlugin {

    private static final Logger LOGGER = LoggerFactory.getLogger(FireWallPlugin.class);

    private final CacheManager cacheManager;

    public FireWallPlugin(final CacheManager cacheManager) {
        super(cacheManager);
        this.cacheManager = cacheManager;
    }


    @Override
    protected Mono<Void> doExecute(ServerWebExchange exchange, IPluginChain chain, ComplexRule rule) {
        String blackList = rule.getBlackList();
        final List<String> blacks = Splitter.on(",")
                .omitEmptyStrings()
                .trimResults()
                .splitToList(blackList);
        InetSocketAddress remoteAddress = exchange.getRequest().getRemoteAddress();
        String clientIp = Objects.requireNonNull(remoteAddress).getAddress().getHostAddress();
        if(StringUtils.isNotBlank(clientIp)) {
            Optional<String> first = blacks.stream()
                    .filter(b -> StringUtils.equals(clientIp, b))
                    .findFirst();
            if(first.isPresent()) {
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.FORBIDDEN);
                return response.writeWith(Mono.just(exchange.getResponse()
                        .bufferFactory().wrap(HttpStatus.FORBIDDEN.getReasonPhrase().getBytes())));
            }

        }
        return chain.execute(exchange);
    }

    @Override
    public String getPluginPhase() {
        return PluginDetailEnum.FIREWALL.getPhase();
    }

    @Override
    public int getCode() {
        return PluginDetailEnum.FIREWALL.getCode();
    }

    @Override
    public String getName() {
        return PluginDetailEnum.FIREWALL.getName();
    }
}
